package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.DimensionsEnum;
import com.tanhua.common.enums.TestTypeEnum;
import com.tanhua.common.mapper.TestQuestionsMapper;
import com.tanhua.common.mapper.TestReportMapper;
import com.tanhua.common.mapper.TestSoulMapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.*;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.support.collections.DefaultRedisList;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TestSoulListService {
    @Autowired
    private TestReportMapper testReportMapper;

    @Autowired
    private TestQuestionsMapper testQuestionsMapper;

    @Autowired
    private TestSoulMapper testSoulMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    public List<TestSoulListVo> getTestSoulList() {
        //由拦截器获取user
        User user = UserThreadLocal.get();
        //根据用户id查询是否有test_report
        QueryWrapper<TestReport> reportWrapper = new QueryWrapper<>();
        reportWrapper.eq("user_id", user.getId());
        List<TestReport> testReportList = testReportMapper.selectList(reportWrapper);
        //获取灵魂试题类型集合
        List<Object> valueList = EnumUtil.getFieldValues(TestTypeEnum.class, "value");
        //查询灵魂试题列表
        QueryWrapper<TestSoul> testWrapper = new QueryWrapper<>();
        testWrapper.in("type", valueList);
        List<TestSoul> testSoulList = testSoulMapper.selectList(testWrapper);
        //查询题目列表
        List<TestQuestions> testQuestionsList = testQuestionsMapper.selectList(new QueryWrapper<>());

        //封装对象
        List<Object> questionList = new ArrayList<>();
        for (int i = 1; i <= testQuestionsList.size(); i++) {
            QuestionsVo questionsVo = new QuestionsVo();
            questionsVo.setId(i + "");
            questionsVo.setQuestion(testQuestionsList.get(i - 1).getQuestion());
            String[] split = testQuestionsList.get(i - 1).getAnswers().split("-");
            List<Object> optionsList = new ArrayList<>();
            for (int j = 1; j <= split.length; j++) {
                QuestionOptionsVo questionOptionsVo = new QuestionOptionsVo();
                questionOptionsVo.setId(j + "");
                questionOptionsVo.setOption(split[j - 1]);
                optionsList.add(questionOptionsVo);
            }
            questionsVo.setOptions(optionsList);
            questionList.add(questionsVo);
        }

        //封装视图对象
        List<TestSoulListVo> testSoulListVoList = new ArrayList<>();
        for (TestSoul testSoul : testSoulList) {
            TestSoulListVo testSoulListVo = new TestSoulListVo();
            testSoulListVo.setId(testSoul.getId().toString());
            testSoulListVo.setName(TestTypeEnum.getDesc(testSoul.getType().intValue()));
            testSoulListVo.setCover(testSoul.getCover());
            testSoulListVo.setLevel(testSoul.getLevel());
            testSoulListVo.setStar(testSoul.getStar().intValue());
            testSoulListVo.setQuestions(questionList);
            testSoulListVo.setIsLock(1);
            testSoulListVo.setReportId(null);
            if (testSoul.getType() == 1) {
                testSoulListVo.setIsLock(0);
            }
            if (CollUtil.isNotEmpty(testReportList)) {
                testSoulListVo.setIsLock(0);
            }
            testSoulListVoList.add(testSoulListVo);
        }
        return testSoulListVoList;
    }

    public String recordTestSoulAnswers(Map<String, Object[]> map) {
        //解析参数
        User user = UserThreadLocal.get();
        Object[] answers = map.get("answers");
        List<String> answerList = new ArrayList<>();
        for (Object answer : answers) {
            LinkedHashMap<String, String> answerMap = (LinkedHashMap<String, String>) answer;
            String questionId = answerMap.get("questionId");
            String optionId = answerMap.get("optionId");
            answerList.add(questionId + optionId);
        }
        //获取得分表
        HashMap<String, Integer> testScoreMap = getTestScoreMap();
        //计算得分
        Integer score = 0;
        for (Map.Entry<String, Integer> testScoreEntry : testScoreMap.entrySet()) {
            for (String key : answerList) {
                if (key.equals(testScoreEntry.getKey())) {
                    score += testScoreEntry.getValue();
                }
            }
        }
        //封装测试报告对象
        TestReport testReport = new TestReport();
        testReport.setUserId(user.getId());
        testReport.setScore(score + "");
        //插入test_report表
        int insert = testReportMapper.insert(testReport);
        //根据userId查询报告,获取最新报告id
        QueryWrapper<TestReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId()).orderByDesc("updated");
        List<TestReport> testReports = testReportMapper.selectList(queryWrapper);
        if (CollUtil.isNotEmpty(testReports)) {
            Long id = testReports.get(0).getId();
            return id.toString();
        }
        return null;
    }

    public static HashMap<String, Integer> getTestScoreMap() {
        HashMap<String, Integer> scoreMap = new HashMap<>();
        //第一题
        scoreMap.put("11", 2);
        scoreMap.put("12", 4);
        scoreMap.put("13", 6);
        scoreMap.put("14", 3);
        //第二题
        scoreMap.put("21", 6);
        scoreMap.put("22", 4);
        scoreMap.put("23", 7);
        scoreMap.put("24", 2);
        //第三题
        scoreMap.put("31", 4);
        scoreMap.put("32", 2);
        scoreMap.put("33", 5);
        //第四题
        scoreMap.put("41", 4);
        scoreMap.put("42", 6);
        scoreMap.put("43", 2);
        scoreMap.put("44", 1);
        scoreMap.put("45", 4);
        //第五题
        scoreMap.put("51", 6);
        scoreMap.put("52", 6);
        scoreMap.put("53", 6);
        scoreMap.put("54", 6);
        scoreMap.put("55", 6);
        scoreMap.put("56", 6);
        scoreMap.put("57", 6);
        //第六题
        scoreMap.put("61", 4);
        scoreMap.put("62", 4);
        scoreMap.put("63", 4);
        scoreMap.put("64", 4);
        //第七题
        scoreMap.put("71", 3);
        scoreMap.put("72", 3);
        scoreMap.put("73", 3);
        //第八题
        scoreMap.put("81", 4);
        scoreMap.put("82", 4);
        scoreMap.put("83", 4);
        scoreMap.put("84", 4);
        //第九题
        scoreMap.put("91", 5);
        scoreMap.put("92", 5);
        scoreMap.put("93", 5);
        scoreMap.put("94", 5);
        scoreMap.put("95", 5);
        scoreMap.put("96", 5);
        //第10题
        scoreMap.put("101", 4);
        scoreMap.put("102", 4);
        scoreMap.put("103", 4);
        scoreMap.put("104", 4);
        scoreMap.put("105", 4);
        scoreMap.put("106", 4);

        return scoreMap;
    }

    public TestReportVo getTestReport(Long reportId) {
        //获取参数
        User user = UserThreadLocal.get();
        //根据报告id查询test_report
        TestReport testReport = testReportMapper.selectById(reportId);
        if (ObjectUtil.isEmpty(testReport)) {
            return null;
        }
        //根据分数获取报告类型
        HashMap<String, String> reportType = getReportType(Integer.parseInt(testReport.getScore()));
        String conclusion = reportType.get("conclusion");
        String cover = reportType.get("cover");
        //根据分数查询test_report,获取user_id集合
        QueryWrapper<TestReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("score", testReport.getScore());
        List<TestReport> testReports = testReportMapper.selectList(queryWrapper);
        //获取id集合
        List<Object> userIdList = CollUtil.getFieldValues(testReports, "userId");
        //根据id集合获取user_info
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", userIdList);
        List<UserInfo> userInfoList = userInfoMapper.selectList(wrapper);
        List<Object> similarYouVos = new ArrayList<>();
        if (CollUtil.isNotEmpty(userInfoList)) {
            for (UserInfo userInfo : userInfoList) {
                SimilarYouVo similarYouVo = new SimilarYouVo();
                similarYouVo.setId(userInfo.getUserId().intValue());
                similarYouVo.setAvatar(userInfo.getLogo());
                similarYouVos.add(similarYouVo);
            }
        }
        //封装DimensionsVo
        List<Object> dimensionsVos = new ArrayList<>();
        for (int i = 1; i <= 4; i++) {
            DimensionsVo dimensionsVo = new DimensionsVo();
            int randomInt = RandomUtil.randomInt(60, 100);
            dimensionsVo.setValue(randomInt+"%");
            dimensionsVo.setKey(DimensionsEnum.getDesc(i));
            dimensionsVos.add(dimensionsVo);
        }
        //封装视图对象
        TestReportVo testReportVo = new TestReportVo();
        testReportVo.setConclusion(conclusion);
        testReportVo.setCover(cover);
        testReportVo.setDimensions(dimensionsVos);
        testReportVo.setSimilarYou(similarYouVos);
        return testReportVo;
    }

    public HashMap<String, String> getReportType(Integer score) {
        HashMap<String, String> map = new HashMap<>();
        if (score < 21) {
            map.put("conclusion", "猫头鹰：他们的共同特质为重计划、条理、细节精准。在行为上，" +
                    "表现出喜欢理性思考与分析、较重视制度、结构、规范。他们注重执行游戏规则、" +
                    "循规蹈矩、巨细靡遗、重视品质、敬业负责。");
            map.put("cover", "https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/owl.png");
        } else if (score >= 21 && score < 40) {
            map.put("conclusion", "白兔型：平易近人、敦厚可靠、避免冲突与不具批判性。在行为上，" +
                    "表现出不慌不忙、冷静自持的态度。他们注重稳定与中长程规划，现实生活中，" +
                    "常会反思自省并以和谐为中心，即使面对困境，亦能泰然自若，从容应付。");
            map.put("cover", "https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/rabbit.png");
        } else if (score >= 41 && score < 55) {
            map.put("conclusion", "狐狸型 ：人际关系能力极强，擅长以口语表达感受而引起共鸣，" +
                    "很会激励并带动气氛。他们喜欢跟别人互动，重视群体的归属感，基本上是比较" +
                    "「人际导向」。由于他们富同理心并乐于分享，具有很好的亲和力，在服务业、" +
                    "销售业、传播业及公共关系等领域中，狐狸型的领导者都有很杰出的表现。");
            map.put("cover", "https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/fox.png");
        } else if (score > 55) {
            map.put("conclusion", "狮子型：性格为充满自信、竞争心强、主动且企图心强烈，是个有决断力的领导者。" +
                    "一般而言，狮子型的人胸怀大志，勇于冒险，看问题能够直指核心，并对目标全力以赴。" +
                    "他们在领导风格及决策上，强调权威与果断，擅长危机处理，此种性格最适合开创性与改革性的工作。");
            map.put("cover", "https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/lion.png");
        }
        return map;
    }
}
